//
//  DaLeTou2ViewController.m
//  EasyToo
//
//  Created by linshengqin on 13-6-15.
//
//

#import "DaLeTou2ViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "LotteryCount.h"
#import <QuartzCore/QuartzCore.h>
#import "NetworkAlertView.h"
#import "CaiPiaoQiCiInfo.h"
#import "CaiPiaoConfirmViewController.h"
#import "CaiPiaoLogic.h"
@interface DaLeTou2ViewController ()
{
    int redArray[33];
    int blueArray[16];
}
@end

@implementation DaLeTou2ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.navigationItem setTitle:@"大乐透"];
     [self.view setBackgroundColor:BackgroundColor];

    [self initData];
    [self initMainView];
    [self initLable];
    [self initButton];
	// Do any additional setup after loading the view.
    [self becomeFirstResponder]; // for shaking

}

-(void)initData
{
    _red_btnArray = [[NSMutableArray alloc]init];
    _blue_btnArray = [[NSMutableArray alloc]init];
    caipiao_model = [CaiPiaoModel sharedata];
    [caipiao_model resetPara];
    [[NetworkAlertView shareView] showNetView];
    
    [CaipiaoManager shareManager].delegate = self;
    [[CaipiaoManager shareManager] CaiPiaoQiCi:@"6" Qici:@""];
    
}

-(void)initMainView
{
    _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [DeviceUtil getScreenWidth], [DeviceUtil getScreenHeight])];
    [self.view addSubview:_bgScrollView];
    _bgScrollView.contentSize = CGSizeMake(320, 700);
    _bgScrollView.showsVerticalScrollIndicator = YES;
    
    _redView = [[UIView alloc]initWithFrame:CGRectMake(20, 50, _bgScrollView.frame.size.width-40, 200)];
    _redView.layer.borderColor = [UIColor grayColor].CGColor;
    _redView.layer.borderWidth = 1 ;
    _redView.layer.cornerRadius = 10 ;
    [_bgScrollView addSubview:_redView];
    
    _blueView = [[UIView alloc]initWithFrame:CGRectMake(20, 300, _bgScrollView.frame.size.width-40, 120)];
    _blueView.layer.borderColor = [UIColor grayColor].CGColor;
    _blueView.layer.borderWidth = 1 ;
    _blueView.layer.cornerRadius = 10 ;
    [_bgScrollView addSubview:_blueView];
}

-(void)onClickCancle:(id)sender
{
    printf("cancle\n");
    for (UIButton *button in _red_btnArray) {
        button.selected = NO;
    }
    
    for (UIButton *button in _blue_btnArray) {
        button.selected = NO;
    }
    
}

-(void)onClickConfirm:(id)sender
{
    [self resignFirstResponder];
    int redCount =0,blueCount=0;
    //    [self jumpLogic];
    for (UIButton *button in _red_btnArray) {
        if(button.selected)
        {
            redCount++;
        }
    }
    
    for (UIButton *button in _blue_btnArray) {
        if(button.selected)
            blueCount++;
    }
    
    if( redCount<5 || blueCount<2)
    {
        UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"红球不少于5个蓝球不少于2个" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [baseAlert show];
        return;
    }
    printf("redcount is:%d,bluecount is:%d\n",redCount,blueCount);
    
    if( [[CaiPiaoLogic shareInstance] cmpTime] != NSOrderedAscending )
    {
        UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"投注时间已过" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [baseAlert show];
        return;
    }

    
    NSMutableString* redString = [[NSMutableString alloc]init];
    NSMutableString* blueString = [[NSMutableString alloc]init];
    NSMutableString* totalString = [[NSMutableString alloc]init];
    int flag = 1;
    for (UIButton *button in _red_btnArray) {
        if(button.selected)
        {
            if( flag==1 )
            {
                [redString appendString:button.titleLabel.text];
                flag = 0;
            }
            else
            {
                [redString appendFormat:@",%@",button.titleLabel.text];
            }
            button.selected = NO;
        }
    }
    flag = 1;
    for (UIButton *button in _blue_btnArray) {
        if(button.selected)
        {
            if( flag )
            {
                [blueString appendString:button.titleLabel.text];
                flag = 0;
            }
            else
            {
                [blueString appendFormat:@",%@",button.titleLabel.text];
            }
            button.selected = NO;
        }
    }
    [totalString appendFormat:@"%@|%@",redString,blueString];
    
    NSLog(@"totalString is:%@\n",totalString);
    [caipiao_model.stakeList addObject:totalString];
    [caipiao_model.listNum addObject:[NSNumber numberWithLong:totalNum]];
    [caipiao_model.listPrice addObject:[NSNumber numberWithLong:totalPirce]];
    caipiao_model.lType = 6;
    CaiPiaoConfirmViewController  *confirm = [[[CaiPiaoConfirmViewController alloc]init]autorelease];
    [self.navigationController pushViewController:confirm animated:YES];
    
    
}

-(void) initLable
{
    tips = [[[UILabel alloc] initWithFrame:CGRectMake(20, 10, 170, 30)]autorelease];
    tips.text =  @"至少选择5个红球";
    tips.font = [UIFont boldSystemFontOfSize:12.0f];  //UILabel的字体大小
    tips.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    [tips setBackgroundColor:[UIColor clearColor]];
    
    //    [self.view addSubview:tips];
    [_bgScrollView addSubview:tips];
    
    UIButton* tips_button = [UIButton buttonWithType:UIButtonTypeCustom];
    tips_button.frame = CGRectMake( 220, 10,60, 30);
    tips_button.titleLabel.font = [UIFont boldSystemFontOfSize:12.0f];
    
    [tips_button setTitle:[NSString stringWithFormat:@"%@",@"机选红球"] forState:UIControlStateNormal];
    [tips_button setBackgroundColor:[UIColor clearColor]];
    [tips_button setBackgroundImage:[UIImage imageNamed:@"cp_sshongq_bg"] forState:UIControlStateNormal ];
    [tips_button addTarget:self action:@selector(randRedBall:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:tips_button];
    
    UILabel *tips2 = [[[UILabel alloc] initWithFrame:CGRectMake(20, _redView.frame.origin.y+_redView.frame.size.height+15, 170, 30)]autorelease];
    tips2.text =  @"至少选择2个蓝球";
    tips2.font = [UIFont boldSystemFontOfSize:12.0f];  //UILabel的字体大小
    tips2.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    [tips2 setBackgroundColor:[UIColor clearColor]];
    
    //    [self.view addSubview:tips];
    [_bgScrollView addSubview:tips2];
    
    UIButton* tips_button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    tips_button2.frame = CGRectMake( 220, _redView.frame.origin.y+_redView.frame.size.height+15,60, 30);
    tips_button2.titleLabel.font = [UIFont boldSystemFontOfSize:12.0f];
    
    [tips_button2 setTitle:[NSString stringWithFormat:@"%@",@"机选蓝球"] forState:UIControlStateNormal];
    [tips_button2 setBackgroundColor:[UIColor clearColor]];
    [tips_button2 setBackgroundImage:[UIImage imageNamed:@"cp_sslanq_bg.png"] forState:UIControlStateNormal ];
    [tips_button2 addTarget:self action:@selector(randBlueBall:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:tips_button2];
}
#define MAX_RED_NUM 35
#define MAX_BULE_NUM 12
-(void) initButton
{
    
    /*红球*/
    int red_num = 0;
    while (red_num<MAX_RED_NUM) {
        
        m_button = [UIButton buttonWithType:UIButtonTypeCustom];
        m_button.frame = CGRectMake((red_num%7)*40, (red_num/7)*40, 40, 40);
        m_button.tag=red_num+1;
        // Set the font and color
        [m_button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [m_button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        
        m_button.titleLabel.font = [UIFont boldSystemFontOfSize:10.0f];
        
        [m_button setTitle:[NSString stringWithFormat:@"%02d",red_num+1] forState:UIControlStateNormal];
        
        [m_button setBackgroundColor:[UIColor clearColor]];
        [m_button setBackgroundImage:[UIImage imageNamed:@"cp_ssqiu_bg"] forState:UIControlStateNormal ];
        [m_button setBackgroundImage:[UIImage imageNamed:@"cp_ssqiured_bg"]forState:UIControlStateSelected];
        
        [m_button addTarget:self action:@selector(touristEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_red_btnArray addObject:m_button];
        [_redView addSubview:m_button];
        red_num++;
    }
    
    /*蓝球*/
    int blue_num = 0;
    while (blue_num<MAX_BULE_NUM) {
        
        m_button = [UIButton buttonWithType:UIButtonTypeCustom];
        m_button.frame = CGRectMake((blue_num%7)*40, (blue_num/7)*40, 40, 40);
        m_button.tag=blue_num+1;
        // Set the font and color
        [m_button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [m_button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        m_button.titleLabel.font = [UIFont boldSystemFontOfSize:10.0f];
        
        [m_button setTitle:[NSString stringWithFormat:@"%02d",blue_num+1] forState:UIControlStateNormal];
        
        [m_button setBackgroundColor:[UIColor clearColor]];
        [m_button setBackgroundImage:[UIImage imageNamed:@"cp_ssqiu_bg"] forState:UIControlStateNormal ];
        [m_button setBackgroundImage:[UIImage imageNamed:@"cp_ssqiublue_bg"]forState:UIControlStateSelected];
        
        [m_button addTarget:self action:@selector(touristEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_blue_btnArray addObject:m_button];
        [_blueView addSubview:m_button];
        blue_num++;
    }
    
    UIButton* m_cleanall = [UIButton buttonWithType:UIButtonTypeCustom];
    m_cleanall.frame = CGRectMake(40,_blueView.frame.origin.y+_blueView.frame.size.height+20, 100, 40);
    [m_cleanall setTitle:[NSString stringWithFormat:@"%@",@"清空全部"] forState:UIControlStateNormal];
    [m_cleanall setBackgroundColor:[UIColor clearColor]];
    [m_cleanall setBackgroundImage:[UIImage imageNamed:@"clear_all"] forState:UIControlStateNormal ];
    [m_cleanall addTarget:self action:@selector(onClickCancle:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:m_cleanall];
    
    UIButton* m_confirm = [UIButton buttonWithType:UIButtonTypeCustom];
    m_confirm.frame = CGRectMake([DeviceUtil getScreenWidth]/2+20, _blueView.frame.origin.y+_blueView.frame.size.height+20, 100, 40);
    [m_confirm setTitle:[NSString stringWithFormat:@"%@",@"下一步"] forState:UIControlStateNormal];
    [m_confirm setBackgroundColor:[UIColor clearColor]];
    [m_confirm setBackgroundImage:[UIImage imageNamed:@"xyb"] forState:UIControlStateNormal ];
    [m_confirm addTarget:self action:@selector(onClickConfirm:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:m_confirm];
}

-(void)randRedBall:(id)sender
{
    int num = 5;
    for (UIButton *button in _red_btnArray) {
        button.selected = NO;
    }
    _toolbarLabel.text = [NSString stringWithFormat:@"共%d注 %d元",0,0];
    for( int i=0;i<35;i++)
    {
        redArray[i]=i;
    }
    
    //做100次随机交换
    for (int i=0;i<100;i++)
    {
        int x = arc4random() % 35;
        int y = arc4random() % 35;
        [self change:x num2:y];
    }
    
    for( int i=0;i<num;i++)
    {
        UIButton* btn = ([_red_btnArray objectAtIndex:redArray[i]]);
        btn.selected=YES;
    }
    [self touristEvent:nil];
}

-(void)randBlueBall:(id)sender
{
    for (UIButton *button in _blue_btnArray) {
        button.selected = NO;
    }
    int x = arc4random() % 12;
    UIButton* btn = [_blue_btnArray objectAtIndex:x];
    btn.selected = YES;
    
    int y = arc4random() % 12;
    while( x == y )
    {
        y = arc4random() % 12;
    }
    btn = [_blue_btnArray objectAtIndex:y];
    btn.selected = YES;
    [self touristEvent:nil];
}

-(void)touristEvent:(id)sender
{
    UIButton *button = (UIButton *)sender;
    button.selected = !button.selected;
    
    int red_count = 0;
    int blue_count = 0;
    for (UIButton *button in _red_btnArray) {
        if( button.selected == YES )
            red_count++;
    }
    
    for (UIButton *button in _blue_btnArray) {
        if( button.selected == YES )
            blue_count++;
    }
    printf("red count is:%d,blue count is:%d\n",red_count,blue_count);
    long m_totalCount = getLotteryCount(red_count,5)*getLotteryCount(blue_count,2);
    long m_totalPirce = 2*m_totalCount;
    if(totalPirce > 20000)
    {
        printf("不能超过20000元\n");
        UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"不能超过20000元" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [baseAlert show];
        button.selected = !button.selected;
    }
    else
    {
        totalNum = m_totalCount;
        totalPirce = m_totalPirce;
        self.navigationItem.title = [NSString stringWithFormat:@"共%ld注 %ld元",totalNum,totalPirce];
    }
}

#pragma mark shark delegate

- (BOOL) canBecomeFirstResponder
{
    return YES;
}


-(void)change:(int)first num2:(int)second
{
    int temp = redArray[first];
    redArray[first] = redArray[second];
    redArray[second] = temp;
}
- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event

{
    
    //检测到摇动
    printf("shaking begin!\n");
    
}



- (void) motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event

{
    
    //摇动取消
    
}



- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event

{
    
    //摇动结束
    
    if (event.subtype == UIEventSubtypeMotionShake) {
        
        //something happens
        printf("shaking end!\n");
        for (UIButton *button in _red_btnArray) {
            button.selected = NO;
        }
        
        for (UIButton *button in _blue_btnArray) {
            button.selected = NO;
        }
        _toolbarLabel.text = [NSString stringWithFormat:@"共%d注 %d元",0,0];
        for( int i=0;i<35;i++)
        {
            redArray[i]=i;
        }
        
        //做100次随机交换
        for (int i=0;i<100;i++)
        {
            int x = arc4random() % 35;
            int y = arc4random() % 35;
            [self change:x num2:y];
        }
        
        for( int i=0;i<5;i++)
        {
            UIButton* btn = ([_red_btnArray objectAtIndex:redArray[i]]);
            btn.selected=YES;
        }
        
        int x = arc4random() % 12;
        UIButton* btn = [_blue_btnArray objectAtIndex:x];
        btn.selected = YES;
        
        int y = arc4random() % 12;
        while( x == y )
        {
            y = arc4random() % 12;
        }
        btn = [_blue_btnArray objectAtIndex:y];
        btn.selected = YES;
        
        [self randRedBall:nil];
        [self randBlueBall:nil];
        [self touristEvent:nil];
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onSearchQiCiFinish:(BOOL)isSuccess
                      QiCi:(NSMutableArray*)qiciInfoArray;

{
    if(isSuccess)
    {
        [[NetworkAlertView shareView]delView];
        printf("333311\n");
        printf("444411\n");
        
        CaiPiaoQiCiInfo* info = qiciInfoArray[0];
        caipiao_model.issue = info.issue;
        caipiao_model.startTime = info.startTime;
        caipiao_model.endTime = info.endTime;
        NSLog(@"issue is:%@,startTime is:%@,endTime is:%@\n",caipiao_model.issue,caipiao_model.startTime,caipiao_model.endTime);
        
    }
    else
    {
        printf("fdfdffdf\n");
        [[NetworkAlertView shareView]delView];
        
    }
}

- (void)dealloc
{
    [CaipiaoManager shareManager].delegate = nil;
    [super dealloc];
}

@end
